<template>
  <div class="content">
    <div class="left-box">
      <ProTable
        ref="leftProTable"
        title="服务商列表"
        :columns="leftColumns"
        :request-api="getStoreGroupList"
        :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
        :data-callback="dataCallback"
        @row-click="onRadio"
      >
        <!-- <template #tableHeader>
          <el-button type="primary" :icon="Setting" @click="openDialog('新增')"> 价格设置 </el-button>
        </template> -->
        <template #operation="scope">
          <el-button v-auth="'editStore'" type="primary" link :icon="EditPen" @click.stop="openServiceDialog('编辑', scope.row)">
            编辑
          </el-button>
          <el-button v-auth="'cancel'" type="primary" link :icon="Close" @click.stop="cancelRow(scope.row)">
            取消服务商
          </el-button>
        </template>
      </ProTable>
    </div>
    <div class="right-box">
      <ProTable
        ref="rightProTable"
        title="商户列表"
        :columns="rightColumns"
        :request-api="getGroupStoreList"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <template #tableHeader>
          <el-button v-auth="'addStore'" type="primary" :icon="CirclePlus" @click="addGroup"> 新增商户 </el-button>
        </template>
        <template #operation="scope">
          <el-dropdown trigger="hover">
            <el-button type="primary">
              操作菜单
              <el-icon><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button v-auth="'editStore'" type="primary" link :icon="EditPen" @click.stop="openMerchantDialog(scope.row)">
                    编辑
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    v-auth="'check'"
                    v-if="scope.row.smsCheckFlag"
                    type="primary"
                    link
                    :icon="Check"
                    @click.stop="checkRow(scope.row.smsCheckFlag === 1 ? '审核' : '取消审核', scope.row)"
                  >
                    {{ scope.row.smsCheckFlag === 1 ? "审核签名" : "取消审核" }}
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button v-auth="'set'" type="primary" link :icon="Check" @click.stop="setRow(scope.row)">
                    设为服务商
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button v-auth="'reSet'" type="primary" link :icon="Refresh" @click="resetPassword(scope.row)">
                    重置密码
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" link :icon="User" @click="authorizationMeituan(scope.row.id)"> 美团授权 </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" link :icon="User" @click="authorizationElement(scope.row.id)"> 饿了么授权 </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    type="primary"
                    link
                    :icon="User"
                    @click="
                      async () => {
                        await createActivationCodeAPI({ id: scope.row.id });
                        rightProTable?.getTableList();
                      }
                    "
                  >
                    创建激活码
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ProTable>
    </div>
    <ByGroupDialog ref="byGroupDialogRef" />
    <ServiceDialog ref="serviceDialogRef" />
    <MerchantDialog ref="merchantDialogRef" />
  </div>
</template>
<script setup lang="tsx" name="service">
import { Operation } from "@/api/interface";
import {
  authorizationElementAPI,
  authorizationMeituanAPI,
  cancelStoreGroup,
  createActivationCodeAPI,
  createByGroup,
  doSignCheck,
  editStore,
  editStoreGroup,
  getGroupStoreList,
  getStoreGroupList,
  setStoreGroup
} from "@/api/modules/operation";
import { resetPas } from "@/api/modules/system";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { formatDate } from "@/utils/date-formatter";
import { downloadFile } from "@/utils/downLoad";
import ByGroupDialog from "@/views/operation/components/ByGroupDialog.vue";
import MerchantDialog from "@/views/operation/components/MerchantDialog.vue";
import ServiceDialog from "@/views/operation/components/ServiceDialog.vue";
import { Check, CirclePlus, Close, EditPen, Refresh, User } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ref } from "vue";

const leftProTable = ref<ProTableInstance>();
const rightProTable = ref<ProTableInstance>();
const initParam = ref({ groupId: 0 });

const leftColumns: ColumnProps<Operation.ResStoreGroupList>[] = [
  { type: "radio", width: 60 },
  { sortable: true, prop: "number", label: "编码", align: "left", minWidth: 120, search: { el: "input" } },
  { sortable: true, prop: "name", label: "服务商名称", minWidth: 130, align: "left" },
  { sortable: true, prop: "balance", label: "账户余额", minWidth: 110, align: "left" },
  { sortable: true, prop: "number", label: "邀请码", minWidth: 100, align: "left" },
  { sortable: true, prop: "linkMan", label: "联系人", minWidth: 120, align: "left" },
  { sortable: true, prop: "mobile", label: "联系电话", minWidth: 164, align: "left" },
  { prop: "operation", label: "操作", minWidth: 200 }
];

const rightColumns: ColumnProps<Operation.ResGroupStoreList>[] = [
  { type: "index", label: "序号", width: 60 },
  {
    sortable: true,
    prop: "id",
    label: "商户ID",
    align: "left",
    width: 100,
    search: { el: "input", label: "商户搜索", key: "storeName" }
  },
  { sortable: true, prop: "storeName", label: "商户名称", minWidth: 180, align: "left" },
  { sortable: true, prop: "userName", label: "用户名称", width: 110, align: "left" },
  { sortable: true, prop: "activationCode", label: "邀请码", minWidth: 100, align: "left" },
  { sortable: true, prop: "mobile", label: "联系电话", minWidth: 120, align: "left" },
  { sortable: true, prop: "createTime", label: "注册时间", minWidth: 164, align: "left" },
  { sortable: true, prop: "defaultPassWord", label: "默认密码", minWidth: 164, align: "left" },
  { sortable: true, prop: "endDate", label: "到期时间", minWidth: 164, align: "left" },
  { sortable: true, prop: "smsSign", label: "短信签名", minWidth: 120, align: "left" },
  { sortable: true, prop: "facCode", label: "激活码", minWidth: 100, align: "left" },
  { sortable: true, prop: "smsCheckFlagName", label: "签名审核状态", minWidth: 164, align: "left" },
  // {sortable: true, prop: "smsCheckFlag", label: "签名审核状态", minWidth: 120, enum: checkFlag },
  { sortable: true, prop: "smsSignApplyTime", label: "签名申请时间", minWidth: 164, align: "left" },
  { sortable: true, prop: "parentStoreId", label: "上级商户编码", minWidth: 140, align: "left" },
  { sortable: true, prop: "parentStoreName", label: "上级商户名称", minWidth: 140, align: "left" },
  { sortable: true, prop: "linkMan", label: "联系人", minWidth: 164, align: "left" },
  { sortable: true, prop: "address", label: "门店详细信息", minWidth: 164, align: "left" },
  { prop: "operation", label: "操作", width: 128, fixed: "right" }
];

// 设置为服务商
const setRow = async (params: Operation.ResGroupStoreList) => {
  await useHandleData(setStoreGroup, { id: params.id }, `设置【${params.storeName}】为服务商`);
  leftProTable.value?.getTableList();
};

// 取消为服务商
const cancelRow = async (params: Operation.ResGroupStoreList) => {
  await useHandleData(cancelStoreGroup, { id: params.id }, `取消【${params.name}】为服务商`);
  leftProTable.value?.getTableList();
  rightProTable.value?.getTableList();
};

// 审核短信签名
const checkRow = async (message: string, params: Operation.ResGroupStoreList) => {
  await useHandleData(doSignCheck, { id: params.id }, `${message}【${params.storeName}】短信签名`);
  rightProTable.value?.getTableList();
};

const onRadio = (row: Operation.ResStoreGroupList) => {
  if (initParam.value.groupId !== row.id) {
    initParam.value.groupId = row.id;
  }
};

const resetPassword = async (params: Operation.ResGroupStoreList) => {
  await useHandleData(resetPas, { id: params.id }, `重置【${params.storeName}】密码`);
};

const addGroup = () => {
  if (initParam.value.groupId !== 0) {
    openByGroupDialog("新增", {
      groupId: initParam.value.groupId,
      isCreateFacCode: true,
      passWord: "",
      createCount: 1,
      endDate: formatDate(366, "start", "yyyy-MM-dd")
    });
  } else {
    ElMessage.error("请选中一个服务商");
  }
};

const dataCallback = (data: any) => {
  leftProTable.value.element.clearSelection();
  initParam.value.groupId = 0;
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

const byGroupDialogRef = ref<InstanceType<typeof ByGroupDialog> | null>(null);
const openByGroupDialog = (title: string, row: Partial<Operation.ResGroupStoreList> = {}) => {
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: createByGroup,
    getTableList: rightProTable.value?.getTableList
  };
  byGroupDialogRef.value?.acceptParams(params);
};

const serviceDialogRef = ref<InstanceType<typeof ServiceDialog> | null>(null);
const openServiceDialog = (title: string, row: Partial<Operation.ResStoreGroupList> = {}) => {
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: editStoreGroup,
    getTableList: leftProTable.value?.getTableList
  };
  serviceDialogRef.value?.acceptParams(params);
};

const merchantDialogRef = ref<InstanceType<typeof MerchantDialog> | null>(null);
const openMerchantDialog = (row: Partial<Operation.ResGroupStoreList> = {}) => {
  const params = {
    title: "商户资料",
    isView: false,
    row: { ...row },
    isService: true,
    api: editStore,
    getTableList: rightProTable.value?.getTableList
  };
  merchantDialogRef.value?.acceptParams(params);
};

// 美团授权
const authorizationMeituan = async (id: number) => {
  const res = await authorizationMeituanAPI({ id });
  downloadFile(res.data as string, "", true);
};

// 饿了么授权
const authorizationElement = async (id: number) => {
  const res = await authorizationElementAPI({ id });
  downloadFile(res.data as string, "", true);
};
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  width: 100%;
  height: 100%;
  .left-box {
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    width: 470px;
    height: 100%;
  }
  .right-box {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: calc(100% - 470px);
    height: 100%;
  }
}
</style>
